from datetime import datetime

# 获取当前日期

today = datetime.now() 

print('今天是星期', today.weekday()+1)

# 如果不使用 datetime 内建函数计算周几，
# 则可以确定一个已知周几的基准日期，计算日期间隔，
# 以便推算这个日期是周几

# is_leap_year 判断是否为闰年

is_leap_year = lambda y: (y % 4 == 0 and y % 100 != 0) or y % 400 == 0

# get_days 获得某年某月的天数

def get_days(year, month):
    days = {
        1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
        7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
    }
    if month == 2 and is_leap_year(year):
        return 29
    else:
        return days[month]


def is_valid_date(y,m,d):
    if m < 1 or m > 12:
        return False
    else:
        if d < 1 or d > get_days(y,m):
            return False
    return True

y = int(input('输入出生年'))
m = int(input('输入出生月'))
d = int(input('输入出生日'))

birthday = datetime(y,m,d)

print('她的生日', '{}/{}/{}'.format(y,m,d), '周', birthday.weekday()+1)

print('电脑日期', '{}/{}/{}'.format(today.year, today.month, today.day))

# 日期间隔计算

def gap_between_dates(date_a, date_b):
    ay, am, ad = date_a
    by, bm, bd = date_b

    # sum1: days passed in year a
    sum1 = 0
    for i in range(1, am):
        sum1 += get_days(ay, i)
    sum1 += ad

    # sum2: days passed in year b
    sum2 = 0
    for i in range(1, bm):
        sum2 += get_days(by, i)
    sum2 += bd

    # two dates are in the same year
    if ay == by: return abs(sum2 - sum1)
    else:
        # swap if date a is later than date b
        if ay > by:
            ay, by = by, ay
            sum1, sum2 = sum2, sum1

        sum0 = 0

        # days of the whole years *between* ay and by
        for i in range(ay + 1, by):
            sum0 += 366 if is_leap_year(i) else 365

        # days left in year a
        sum0 += (365 + (1 if is_leap_year(ay) else 0) - sum1)
        # days passed in year b
        sum0 += sum2

        return sum0


# 两个 datetime 对象相减可以得到 days_delta 对象，
# 使用其 days 属性可以得到差值
# from datetime import datetime
# a = datetime(2021,1,1)
# b = datetime(2021,2,1)
# 则 (a - b).days 的为 -31

a = (y,m,d)
b = (today.year, today.month, today.day)

print('他的日龄是：', gap_between_dates(a, b))

